<script setup>
import {useApi} from "../../composables/useApi"
import showTost from '@/components/toast/index.js'
import * as XLSX from "xlsx";
import moment from "moment";
import {storeToRefs} from "pinia"
import {useAppStore} from "../../store/app"
const appStore = useAppStore()
const {nationArr, sexArr} = storeToRefs(appStore)
import {reactive, ref} from "vue"
import TeatherRightDrawaer from "@/pages/platform/components/teatherRightDrawaer.vue";
//基本数据list
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
let teacherList = ref([])
let queryFrom = ref({page: 1, limit: 20, real_name: '', sex: '', nation: '', birth_time: '', entry_time: ''})

const headers = [
  {
    title: "教师姓名",
    align: 'start',
    key: "real_name",
  },
  {
    title: "教师ID",
    align: 'start',

    key: "username",
  },
  {
    title: "性别",
    align: 'start',
    key: "sex",
  },
  {
    title: "民族",
    align: 'start',
    key: "nation",
  },
  {
    title: "出生日期",
    align: 'start',
    key: "birth_time",
  },
  {
    title: "入职日期",
    align: 'start',
    key: "entry_time",
  },
  {
    title: "登录密码",
    align: 'start',
    key: "password",
  },
  {
    title: "操作",
    align: 'end',
    key: "options",
    sortable: false,
  },
]

const getList = async () => {
  const {data} = await useApi('/admin/Api.Teacher/index').post(queryFrom.value)
  console.log(data)
  total.value = data.value.data.total
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.teacher_id
    }
  })
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  data.birth_time = [data.birth_start_time, data.birth_end_time]
  data.entry_time = [data.entry_start_time, data.entry_end_time]
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val)
  let ids = val.data.map(item=>item.teacher_id).toString()
  console.log(ids)
  const {data} = await useApi('/admin/Api.Teacher/delete').post({teacher_id: ids})
  console.log(data.value)
  if (data.value.status == 200) {
    showTost("删除成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if(val.type == 'detail'){
      dialogFlag.value = false
    }
    getList()
  }
}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type:'list'
    }
    confirmMsg.value = `确认删除${data.map(item => item.real_name).toString()}的信息吗`
    isConfirmDialogVisible.value = true
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  const {data} = await useApi('/admin/Api.Teacher/detail').post({teacher_id: item.teacher_id})
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const {data} = await useApi('/admin/Base/downFile').post({type: 1})
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement('a');
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();

  }

}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  form.sex = '女'
  form.nation = '汉族'
  form.birth_time = ''
  form.entry_time = ''
  addDialogFlag.value = false
}


const valid = ref(false)
const form = reactive({
  teacher_id: '',
  real_name: '',//姓名
  sex: '女',//性别
  nation: '汉族',//民族
  birth_time: '',//出生日期
  entry_time: '',//入职日期
  graduate_school: '',//毕业学校
  graduate_major: '',//毕业专业
  home_address: '',//家庭住址
  regis_address: '',//户口地址
  id_card: '',//身份证号
  phonenumber: '',//联系电话
  emergency_contact: '',//紧急联系人
  emergency_phone: '',//紧急联系人电话
  personal_photo: ''

})
const confirmAddTeacher = async (args) => {
  console.log(valid.value)

  if (!valid.value) return
  const {data} = await useApi('/admin/Api.Teacher/add').post(form)
  if (data.value.status == 200) {
    refVForm.value?.reset()
    form.sex = '女'
    form.nation = '汉族'
    form.birth_time = ''
    form.entry_time = ''
    addDialogFlag.value = false
    showTost("新增成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    getList()
  } else {
    console.log(data.value.msg)
    // showTost("新增成功", {duration: 3000, type: "success"})

    showTost(data.value.msg, {duration: 3000, type: "error"})
  }
}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
getList()
const required = (value, name) => !!value || `${name}为必填字段`;
const importExcelRef = ref(null)
const   httpRequest= (e)=> {
  let file = e.file // 文件信息
  if (!file) {
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: 'binary',
        cellDates: true,

      })
      // 取第一张表
      console.log(workbook)
      const exlname = workbook.SheetNames[0]
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
      console.log(exl)
      partPost(exl)
      // 将 JSON 数据挂到 data 里
      let arr = []
      exl.forEach(item => {
        arr.push(item.name)
      })
      console.log(arr)
    } catch (e) {
      console.log('error')
      return false
    }
  }
  fileReader.readAsBinaryString(file)
}
const import_page =ref(1)
const import_limit =ref(10)
const import_percent =ref(0)
const loading =ref(false)

const partPost= async (tableData)=>{
  let perdata = []
  for(let i=(import_page.value-1)*import_limit.value; i<import_page.value*import_limit.value; i++){
    if(tableData[i]){
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil(import_page.value * 100 / total_page)
  loading.value = true
  console.log(perdata)
  perdata =perdata.map(item=>{
    return{
      ...item,
      '出生日期':convertExcelDateFormat(item,'出生日期'),
      '入职日期':convertExcelDateFormat(item,'入职日期'),
    }
})
  console.log(perdata)
  const {data} = await useApi('/admin/Api.Teacher/upload').post({list:perdata})
  if(data.value.status == 200){
      if(import_page.value <= total_page-1){
        import_page.value = import_page.value +1
        partPost(data)
      }else{
        // this.dialog.importDialogstatus = false;
        showTost("导入完成", {duration: 3000, type: "success"})
        addDialogFlag.value =false
        queryFrom.value.page=1
        getList()
        loading.value = false
      }
  }
  // importData(perdata).then(res => {
  //   if(res.status == 200){
  //     if(this.import_page <= total_page-1){
  //       this.import_page = this.import_page +1
  //       this.partPost(data)
  //     }else{
  //       this.dialog.importDialogstatus = false;
  //       this.$message({message: '导入完成', type: 'success'})
  //       this.index()
  //       this.loading = false
  //     }
  //   }
  // })
}
const convertExcelDateFormat = (row, columnName)=> {
  //日期转换
  var date = row[columnName]
  if (date === undefined || date === null || date === "") {
    return null;
  }
  //非时间格式问题  返回Invalid date
  let retFormat = moment(date).format('YYYY-MM-DD');
  if (retFormat === "Invalid date"){
    return retFormat;
  }
  return moment(date).add(1, 'days').format('YYYY-MM-DD')
}

const onChangePage = (val)=>{
  queryFrom.value.page =val.page
  queryFrom.value.limit =val.limit
  getList()
}

const currentOptionData = ref({})
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data:[val] ,
    type:'detail'
  }
  confirmMsg.value = `确认删除${val.real_name}的信息吗`
  isConfirmDialogVisible.value = true
}
</script>

<template>
  <div class="content">
    <TeatherRightDrawaer @onHandleDelete="drawaerDelete" @onHandleEdit="onHandleEdit" :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                         :is-drawer-open="dialogFlag"></TeatherRightDrawaer>

    <ConfirmDialog
      v-model:isDialogVisible="isConfirmDialogVisible"
      :handleData="currentOptionData"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!-- 头部 -->
    <TableHeader
      title="教师信息"
      button-text="添加教师"
      @onChange="onChange"
      @onHandle="onHandleDialog"
    />

    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.password="{ item }">
        <div class="d-flex align-start">
          <div class="d-flex flex-column ">
            {{ item.password || "******" }}
          </div>
        </div>
      </template>
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="flex-column cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />

    <!--    添加教师对话框-->
    <VDialog
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
      title="添加教师"
    >
      <div style="width: 600px;"class="dialog-body">
        <AppDrawerHeaderSection
          title="添加教师"
          @cancel="addDialogFlag=false"
        />
        <VDivider/>
        <VCard>
          <PerfectScrollbar
            :options="{ wheelPropagation: false }"
            class="h-60"
          >
            <VCardText>
              <elUpload
                ref="importExcelRef"
                :limit="1"
                :show-file-list="false"
                class="uploadExcelContent"
                :http-request="httpRequest"
              >
                <VBtn
                  type="submit"
                  color="primary"
                  class="me-4 mb-5"
                >
                  <i style="font-size: 24px;margin-right: 6px" class="ri-upload-cloud-fill"></i>
                  上传Excel文件
                </VBtn>
              </elUpload>

              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAddTeacher"
              >
                <VRow>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.real_name"
                      label="姓名"
                      :rules="[(val)=>required(val,'姓名')]"
                      placeholder="请输入姓名"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.sex"
                      :items="sexList"
                      item-title="title"
                      item-value="title"
                      placeholder="请选择性别"
                      label="性别"
                      :rules="[(val)=>required(val,'性别')]"
                      class="input-width-height"
                    />

                  </VCol>

                  <VCol cols="6">
                    <VSelect
                      v-model="form.nation"
                      :items="nationArr"
                      item-title="title"
                      item-value="title"
                      placeholder="请选择民族"
                      label="民族"
                      :rules="[(val)=>required(val,'民族')]"
                      class="input-width-height"
                    />
                  </VCol>
                  <VCol cols="6">
                    <AppDateTimePicker
                      class="input-width-height"
                      v-model="form.birth_time"
                      label="出生日期"
                      placeholder="请选择出生日期"
                      :rules="[(val)=>required(val,'出生日期')]"
                    >
                      <template v-slot:label>
                        <span>出生开始日期</span>
                      </template>
                    </AppDateTimePicker>

                  </VCol>
                  <VCol cols="6">
                    <AppDateTimePicker
                      class="input-width-height"
                      v-model="form.entry_time"
                      label="入职日期"
                      placeholder="请选择入职日期"
                      :rules="[(val)=>required(val,'入职日期')]"

                    > <template v-slot:label>
                      <span>入职日期</span>
                    </template>
                    </AppDateTimePicker>
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.graduate_school"
                      label="毕业院校"
                      :rules="[(val)=>required(val,'毕业院校')]"
                      placeholder="请输入毕业院校"
                    />
                  </VCol>

                  <VCol cols="12">
                    <VTextField
                      v-model="form.graduate_major"
                      label="毕业专业"
                      :rules="[(val)=>required(val,'毕业专业')]"
                      placeholder="请输入毕业专业"
                    />
                  </VCol>

                  <VCol cols="6">
                    <VTextField
                      v-model="form.regis_address"
                      label="户口地址"
                      :rules="[(val)=>required(val,'户口地址')]"
                      placeholder="请输入户口地址"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.home_address"
                      label="家庭住址"
                      :rules="[(val)=>required(val,'家庭住址')]"
                      placeholder="请输入家庭住址"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.id_card"
                      placeholder="身份证号码"
                      maxLength="18"
                      :rules="[(val) => required(val, '身份证号码'), (val) => val.length === 18 || '身份证号码必须是18位']"
                      label="请输入身份证号码"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.phonenumber"
                      maxLength="11"
                      label="手机号"
                      :rules="[(val) => required(val, '手机号'), (val) => val.length === 11 || '手机号必须是11位']"
                      placeholder="请输入手机号"
                    />
                  </VCol>
                  <VCol cols="12">
                    <VRow>
                      <VCol cols="6">
                        <VTextField
                          v-model="form.emergency_contact"
                          label="紧急联系人"
                          :rules="[(val)=>required(val,'紧急联系人')]"
                          placeholder="请输入紧急联系人"
                        />
                      </VCol>
                      <VCol cols="6">
                        <VTextField
                          v-model="form.emergency_phone"
                          maxLength="11"
                          label="手机号"
                          :rules="[(val) => required(val, '联系人手机号'), (val) => val.length === 11 || '联系人手机号必须是11位']"
                          placeholder="请输入联系人手机号"
                        />
                      </VCol>
                    </VRow>
                  </VCol>
                  <VDivider/>
                  <VCol cols="12">
                    <div class="d-flex justify-end">


                      <VBtn
                        color="#fff"
                        class="me-4"
                        @click="downLoadTemplate"
                      >
                        下载上传模板
                      </VBtn>
                      <VBtn
                        color="#fff"
                        class="me-4"
                        @click="resetForm"
                      >
                        取消
                      </VBtn>
                      <VBtn
                        type="submit"
                        color="primary"
                        class="me-4"
                      >
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>

      </div>
    </VDialog>
  </div>

</template>

<style lang="scss" scoped>
.ri-menu-line {
  width: 22px;
  height: 22px;
}

</style>
